import { mapState } from "vuex";
import utils from "@common/utils/utils";
import bus from "@common/components/common/bus";

export default {
    install(Vue) {
        Vue.mixin({
            data() {
                return {
                    timeRefresh: {},
                    componentDialogOption: {
                        visible: false,
                    },
                };
            },
            computed: {
                ...mapState([ 'global_setting' ]),
            },
            methods: {
                fetchData(url, data = {}, error = true, addLog = true, headers = {}) {
                    return this.$store.dispatch('fetchData', { url, data, error, addLog, headers });
                },
                fetchDataNoCatch(url, data = {}, error = true, addLog = true, headers = {}) {
                    return new Promise(resolve => {
                        this.$store.dispatch('fetchData', { url, data, error, addLog, headers }).then(res => {
                            resolve(res);
                        }).catch(() => {
                        });
                    });
                },
                checkSelection(list, multi = false) {
                    if (!this.$utils.isNotEmptyList(list)) {
                        if (multi) {
                            this.$message.error("请先勾选一条或者多条记录");
                        } else {
                            this.$message.error("请先勾选一条记录");
                        }
                        return false;
                    }
                    if (!multi && list.length > 1) {
                        this.$message.error("只能勾选一条记录");
                        return false;
                    }
                    return true;
                },
                async validateForm(ref) {
                    let _this = this;
                    return new Promise(resolve => {
                        if (_this.$refs[ref]) {
                            _this.$refs[ref].validate((valid, object) => {
                                if (valid) {
                                    resolve(true);
                                } else {
                                    try {
                                        let inValidKey = Object.keys(object);
                                        let dom = _this.$refs[inValidKey[0]];
                                        if (dom && dom.$el) {
                                            dom.$el.scrollIntoView({
                                                block: 'center', // 值有 start、center、end、nearest；当前显示在视图区域中间
                                                behavior: 'smooth' // 值有 auto、instant、smooth；缓动动画（当前是慢速的），instant（瞬间）
                                            });
                                            $(dom[0].$el).focus();
                                            $(dom[0].$el).find('input').focus();
                                            resolve(1);
                                        } else if (dom.length > 0 && dom[0].$el) {
                                            dom[0].$el.scrollIntoView({
                                                block: 'center', // 值有 start、center、end、nearest；当前显示在视图区域中间
                                                behavior: 'smooth' // 值有 auto、instant、smooth；缓动动画（当前是慢速的），instant（瞬间）
                                            })
                                            $(dom[0].$el).focus();
                                            $(dom[0].$el).find('input').focus();
                                            resolve(1);
                                        } else {
                                            resolve(0);
                                        }
                                    } catch (e) {
                                        resolve(0);
                                    }
                                }
                            });
                        } else {
                            resolve(0);
                        }
                    }).then(valid => {
                        if (valid === true) {
                            return valid;
                        }
                        if (valid === 0) {
                            let errorItem = _this.$refs[ref].$el.querySelectorAll('.is-error');
                            if (errorItem.length > 0) {
                                let errorInput = errorItem[0].querySelectorAll('.el-input');
                                if (errorInput.length > 0) {
                                    errorItem[0].scrollIntoView({
                                        block: 'center', // 值有 start、center、end、nearest；当前显示在视图区域中间
                                        behavior: 'smooth' // 值有 auto、instant、smooth；缓动动画（当前是慢速的），instant（瞬间）
                                    });
                                    $(errorItem[0]).find('input').focus();
                                }
                            }
                        }
                        return false;
                    });
                },
                setRefToThis(name, ref) {
                    this[name] = ref;
                },
                getActiveTabsContainer() {
                    let tabsWrapper = $('#app').find('.tabs_wrapper');
                    if (tabsWrapper.length > 0) {
                        let activeTabs = $(tabsWrapper).find('.el-tabs__nav').find('.el-tabs__item.is-active');
                        let tabPane = $(activeTabs).attr('aria-controls');
                        let tabContainer = $(tabsWrapper).find(`#${ tabPane }`);
                        return $(tabContainer).find('.tab_content');
                    }
                    return $('#app').find('.app_content');
                },
                resetIndex(datas, field = "_index", baseObj = {}) {
                    let list = [];
                    if (this.$utils.isNotEmptyList(datas)) {
                        datas.forEach((item, index) => {
                            let obj = $.extend({}, baseObj, item);
                            obj[field] = index;
                            list.push(obj);
                        });
                    }
                    return list;
                },
                resetToolbarFilterSelect(datas, field, options) {
                    let list = [];
                    if (this.$utils.isNotEmptyList(datas)) {
                        datas.forEach(item => {
                            let obj = $.extend({}, item);
                            if (item.field === field) {
                                obj.options = options;
                            }
                            list.push(obj);
                        });
                    }
                    return list;
                },
                resetToolbarFilterSelectList(toolbar_filter, paramsData) {
                    return toolbar_filter.map(item => {
                        let obj = $.extend({}, item);
                        if (item.type === 'select') {
                            obj.options = (paramsData[item.field] || []).map(item => {
                                return {
                                    value: item.value,
                                    label: item.display_text,
                                };
                            });
                        }
                        return obj;
                    });
                },
                resetTableSelect(tableOptions, prop, dataList) {
                    let list = [];
                    if (this.$utils.isNotEmptyList(tableOptions.columns)) {
                        tableOptions.columns.forEach(item => {
                            let obj = $.extend({}, item);
                            if (
                                item.prop === prop &&
                                item.elComp &&
                                item.elComp.elType === "select"
                            ) {
                                let comp = $.extend({}, item.elComp);
                                comp.data_list = dataList;
                                obj.elComp = comp;
                            }
                            if (
                                item.prop === prop &&
                                item.editRender &&
                                item.editRender.name === "ElSelect"
                            ) {
                                let comp = $.extend({}, item.editRender);
                                comp.options = dataList;
                                obj.editRender = comp;
                            }
                            list.push(obj);
                        });
                    }
                    return $.extend({}, tableOptions, {
                        columns: list
                    });
                },
                dispatch(componentName, eventName, params) {
                    let parent = this.$parent || this.$root;
                    let name = parent.$options.componentName;
                    while (parent && (!name || name !== componentName)) {
                        parent = parent.$parent;
                        if (parent) {
                            name = parent.$options.componentName;
                        }
                    }
                    if (parent) {
                        parent.$emit.apply(parent, [ eventName ].concat(params));
                    }
                },
                procJpyValue(value) {
                    let val = utils.accDiv4Ceil(value, 10, 4);
                    return utils.accMul(val, 10);
                },
                setTimeRefresh({ type, path, time, callback }) {
                    if (!time) time = window.configs.refreshTime || 1000 * 60 * 5;
                    if (!path) path = this.$route.path;
                    let $this = this;
                    if ($this.timeRefresh[type]) {
                        clearTimeout($this.timeRefresh[type]);
                    }
                    setTimeout(() => {
                        let pathValue = this.$store.state.pathValue;
                        if (pathValue !== path) {
                            return;
                        }
                        if (this.$store.state.pathValue)
                            $this.timeRefresh[type] = setTimeout(() => {
                                // $this.timeRefresh[type] = type;
                                $this.$nextTick(() => {
                                    if (
                                        callback &&
                                        typeof callback === "function"
                                    ) {
                                        return callback();
                                    }
                                    bus.$emit(type);
                                });
                            }, time);
                    }, 100);
                },
                rowColorClassName({ row, rowIndex }) {
                    let color = "";
                    if (row.state === 0 || row.audit_state === 0) {
                        color = "notAuditColor";
                    }
                    return color;
                },
                openAttachView(param_sid, sid) {
                    // 打开新标签页查看
                    let host = window.location.origin;
                    if (this.$utils.isNotEmpty(window.location.pathname)) {
                        host = `${ host }${ window.location.pathname }`
                    }
                    let viewUrl = `${ host }#/view_attach?param_sid=${ param_sid }&sid=${ sid }`;
                    window.open(viewUrl);
                },
                openPaperView(type, sid) {
                    // 打开新标签页查看
                    let host = window.location.origin;
                    if (this.$utils.isNotEmpty(window.location.pathname)) {
                        host = `${ host }${ window.location.pathname }`
                    }
                    let viewUrl = `${ host }#/view_paper?type=${ type }&sid=${ sid }`;
                    window.open(viewUrl);
                },
                getQueryParams(tableOptions, searchForm = {}) {
                    let queryData = $.extend({}, searchForm);
                    if (tableOptions.pagination) {
                        let pageSize = tableOptions.pagination.pageSize;
                        if (utils.isEmpty(pageSize)) {
                            pageSize = window.configs.pageSize;
                        }
                        queryData = $.extend({}, queryData, {
                            pageNo: tableOptions.pagination.pageIndex,
                            pageSize,
                        });
                    }
                    if (tableOptions.sortList) {
                        queryData.sort_list = tableOptions.sortList;
                    }
                    return queryData;
                },
                setTableTotal(options, result) {
                    let pagination = false;
                    if (options.pagination) {
                        pagination = $.extend({}, options.pagination);
                        pagination.total = result && result.page ? (result.page.totalRows || 0) : 0;
                        pagination.totalPage = result && result.page ? (result.page.pages || 0) : 0;
                    }
                    return $.extend({}, options, { pagination });
                },
                setTableIndex(options, index) {
                    let pagination = false;
                    if (options.pagination) {
                        pagination = $.extend({}, options.pagination);
                        pagination.pageIndex = index;
                        pagination.total = 0;
                    }
                    return $.extend({}, options, { pagination });
                },
                resetTablePagination(options) {
                    let pagination = false;
                    if (options.pagination) {
                        pagination = $.extend({}, options.pagination);
                        pagination.pageIndex = 1;
                        pagination.total = 0;
                    }
                    return $.extend({}, options, { pagination });
                },
                async getPrintStyle() {
                    let str = '';
                    let styles = document.querySelectorAll('style,link');
                    for (let i = 0; i < styles.length; i++) {
                        if (process.env.NODE_ENV === 'production' && styles[i].tagName.toLowerCase() === 'link') {
                            try {
                                let url = styles[i].getAttribute("href");
                                let respData = await axios({ url, method: 'get' });
                                str += `<style>${ respData.data }</style>`;
                            } catch (e) {
                                str += styles[i].outerHTML;
                            }
                        } else {
                            str += styles[i].outerHTML;
                        }
                    }
                    return str;
                },
                formatterAmount(row, column, scope, digits = 2, returnNumber = false) {
                    let rowValue = row[column.prop];
                    if (this.$utils.isNotEmpty(rowValue)) {
                        let value = Number(rowValue).toFixed(digits);
                        if (returnNumber) {
                            value = Number(value);
                        }
                        return value;
                    }
                    return '';
                },
                formatterDate(row, column, scope, format) {
                    let rowValue = row[column.prop];
                    if (this.$utils.isNotEmpty(rowValue) && format) {
                        return this.$utils.formatDate(rowValue, format);
                    } else if (this.$utils.isNotEmpty(rowValue)) {
                        return this.$utils.formatDate(rowValue, "yyyy-MM-dd");
                    }
                    return '';
                },
                renderState(h, params, obj) {
                    let { row, column } = params;
                    let rowValue = row[column.prop];
                    let opt = obj[rowValue];
                    if (!opt) {
                        opt = obj.default;
                    }
                    return h('el-tag', {
                        props: opt.props,
                    }, opt.text);
                },
                storeDispatch (method, data) {
                    return this.$store.dispatch(method, data);
                },
                getFileUrl(fileId) {
                    let account = this.$utils.getAccountSetSidEndWithSlash();
                    return `${window.configs.requestPrefix}${this.$api.File_GetFile}${account}${fileId}`;
                },
                getFileWithType(fileId, fileType) {
                    let account = this.$utils.getAccountSetSidEndWithSlash();
                    return `${window.configs.requestPrefix}${this.$api.File_GetFileWithType}${account}${fileId}${fileType}`;
                },
                async getFileWithTypeUrl(fileId) {
                    let result = await this.fetchData(this.$api.File_GetFileInfo, { sid: fileId }, true);
                    if (result.code === 0) {
                        let fileInfo = result.data || {};
                        let account = this.$utils.getAccountSetSidEndWithSlash();
                        return `${window.configs.requestPrefix}${this.$api.File_GetFileWithType}${account}${fileId}${fileInfo.file_type}`;
                    }
                    return '';
                },
                async getFileInfoWithUrl(fileId) {
                    let account = this.$utils.getAccountSetSidEndWithSlash();
                    let result = await this.fetchData(this.$api.File_GetFileInfo, { sid: fileId }, true);
                    if (result.code === 0) {
                        let fileInfo = result.data || {};
                        fileInfo.url = `${window.configs.requestPrefix}${this.$api.File_GetFile}${account}${fileId}`;
                        return fileInfo;
                    }
                    return '';
                },
                openComponentDialog(options, field = 'componentDialogOption') {
                    const _this = this;
                    _this[field] = {
                        visible: true,
                        title: options.title,
                        width: options.width,
                        component: options.component,
                        propsData: options.propsData,
                        noCloseBtn: options.noCloseBtn,
                        btns: options.btns ? options.btns : [
                            {
                                type: 'primary',
                                text: '确定',
                                loading: true,
                                method(option, { component }) {
                                    component && typeof component.confirm === 'function' && component.confirm().then(valid => {
                                        if (valid) {
                                            typeof options.callback === 'function' && options.callback(component);
                                            _this[field] = {
                                                visible: false,
                                            };
                                        }
                                    })
                                },
                            }
                        ],
                        event: typeof options.event === 'function' ? options.event : () => {},
                    };
                },
                jumpRoute(path, query = {}) {
                    if (this.$utils.isNotEmpty(path)) {
                        this.$router.push({ path, query });
                    }
                }
            },
            // 销毁监听事件
            destroyed() {
                for (let i in this.timeRefresh) {
                    clearTimeout(this.timeRefresh[i]);
                }
            },
        });
    }
};
